// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#include <cantor/parser/parser.h>
#include <cantor/transform/dcls/user_spec.h>
#include <cantor/transform/dcls/user_identity.h>
#include <cantor/transform/dcls/auth_option.h>
#include <cantor/transform/expr.h>

namespace cantor::transform {
    void TransUserSpec::resolve_ast(const cantor::parser::UserSpec *node) {
        if (!node) {
            status = turbo::data_loss_error("no UserSpec");
            return;
        }

        user_spec.mutable_user()->Clear();
        if (node->user) {
            TransUserIdentity identity;
            identity.resolve_ast(node->user);
            status = identity.check();
            if (!status.ok()) {
                return;
            }
            *user_spec.mutable_user() = std::move(identity.user_identity);
        }

        user_spec.mutable_auth_opt()->Clear();
        if (node->auth_opt) {
            TransAuthOption option;
            option.resolve_ast(node->auth_opt);
            status = option.check();
            if (!status.ok()) {
                return;
            }
            *user_spec.mutable_auth_opt() = std::move(option.auth_option);
        }
        set_proto_location(node, user_spec.mutable_location());
        set_proto_status(user_spec.mutable_status());
    }

    const turbo::Status &TransUserSpec::check() {
        if (!status.ok()) {
            return status;
        }
        if (user_spec.has_location()) {
            make_missing_required_field("location");
        }
        return status;
    }
    turbo::Status TransUserSpec::resolve_to(turbo::Nonnull<const cantor::parser::UserSpec*> arg, turbo::Nonnull<pb::ast::UserSpec *>out) {
        TransUserSpec trans;
        trans.resolve_ast(arg);
        auto status = trans.check();
        if (!status.ok()) {
            return status;
        }
        *out = std::move(trans.user_spec);
        return status;
    }
} // namespace cantor::transform
